package info.webest.media.files;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;

public class FileManager {

	public enum ContentType {
		AUDIO, VIDEO, IMAGE

	}

	public static ArrayList<String> getFileList(String folder,
			ContentType contentType) {

		ArrayList<String> fileList = new ArrayList<String>();

		FilenameFilter filter = null;
		switch (contentType) {

		case AUDIO:
			filter = new FileFilter.ImageFilter();
			break;

		case VIDEO:
			filter = new FileFilter.ImageFilter();
			break;

		case IMAGE:
			filter = new FileFilter.ImageFilter();
			break;

		}

		File[] items_ = new File(folder).listFiles(filter);

		if (items_ == null) {
			return fileList;
		}

		if (items_.length > 0) {
			for (File item : items_) {
				fileList.add(item.getAbsolutePath());
			}
		}
		return fileList;
	}

	public static int getChildCount(File f) {
		if (!f.isDirectory())
			return 0;

		// get file list
		File[] items = f.listFiles();

		if (items == null) {
			return 0;
		} else {
			return items.length;
		}
	}

	// This function will return size in form of bytes
	public static long getFolderSize(File f) {
		long size = 0;

		String name = f.getPath();
		if (name.equals("/proc") || name.equals("/sys"))
			return size;

		if (f.isDirectory()) {
			File[] files = f.listFiles();
			if (files != null)
				for (File file : files) {
					size += getFolderSize(file);
				}
		} else {
			size = f.length();
		}
		return size;
	}

	@SuppressLint("DefaultLocale")
	public static String getSize(File f) {
		String value = null;

		float Filesize = getFolderSize(f) / 1024;

		if (Filesize >= 1024)
			value = String.format("%.1f M", Filesize / 1024);
		else
			value = String.format("%.1f K", Filesize);

		return value;
	}

	public static String[] getSize() throws IOException {
		String memory = "";
		Process p = Runtime.getRuntime().exec("df /mnt/sdcard");
		InputStream is = p.getInputStream();
		int by = -1;
		while ((by = is.read()) != -1) {
			memory += new String(new byte[] { (byte) by });
		}
		for (String df : memory.split("/n")) {
			if (df.startsWith("/mnt/sdcard")) {
				String[] par = df.split(" ");
				List<String> pp = new ArrayList<String>();
				for (String pa : par) {
					if (!pa.isEmpty()) {
						pp.add(pa);
					}
				}
				return pp.toArray(new String[pp.size()]);

			}
		}
		return null;
	}
}
